import {listArticle, addArticle, updateArticle, removeArticle} from '_api/home/article'
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    articleList: []
  },
  mutations: {
    setArticleList(state, articleList) {
      state.articleList = articleList
    },
    addArticle(state, article) {
      state.articleList.unshift(article);
    },
    updateArticle(state, article) {
      for (let i = 0; i < state.articleList.length; i++) {
        let existsArticle = state.articleList[i];
        if (existsArticle.id === article.id) {
          let keys = Object.keys(article);
          keys.forEach(key => {
            Vue.set(state.articleList[i], key, article[key])
          })
          break
        }
      }
    },
    removeArticle(state, article) {
      state.articleList = state.articleList.filter(existsArticle => {
        if (existsArticle.id !== article.id) {
          return existsArticle;
        }
      })
    }
  },
  actions: {
    // 获取所有项目类型
    listArticle({state, commit}) {
      return _Promise(listArticle(), res => {
        commit('setArticleList', res.data)
      })
    },

    // 添加项目类型
    addArticle({state, commit}, article) {
      return _Promise(addArticle(article), res => {
        commit('addArticle', res.data)
      })
    },

    // 更新项目类型
    updateArticle({state, commit}, article) {
      return _Promise(updateArticle(article), res => {
        commit('updateArticle', res.data)
      })
    },

    // 删除项目类型
    removeArticle({state, commit}, article) {
      return _Promise(removeArticle(article.id), res => {
        commit('removeArticle', article)
      })
    }
  }
}
